package TCPSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author 王艺锡
 * @version 1.0
 */
public class SocketTCP02Client {
    public static void main(String[] args) throws IOException {
        //1.连接服务端(ip,端口)
        //连接本机的9999端口，如果连接成功，则返回一个Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        //2.连接上后，通过 socket.getOutputStream()得到和 Socket对象关联的输出流对象
        OutputStream outputStream = socket.getOutputStream();
        //3.通过输出流，写入数据到数据通道
        outputStream.write("hello,server".getBytes());
        socket.shutdownOutput();//表示输出结束
        //4.获取
        InputStream inputStream = socket.getInputStream();
        byte buf[] = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf)) != -1){
            System.out.println(new String(buf,0,readLen));
        }
        //4.关闭对应的流和socket(必须)
        outputStream.close();
        inputStream.close();
        socket.close();
    }
}

